package com.example.knowleage.threadPool;

import com.google.common.util.concurrent.ThreadFactoryBuilder;

import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;

/**
 * @ClassName FixedThreadPool
 * @Description 预定义线程池
 * @Author KunxianLi
 * Date 2021/4/16 16:11
 * Version 1.0
 **/
public class ThreadPool {

   /**
    *  ExecutorService 的常用方法
    *  execute(Runnable command)  --- 继承自Executor的方法，只接收Runnable
    *  Future<?> submit  ---   有接收runnable和callable两种
    *  invokeAll   ---只支持callable，invokeAll 需要所有线程都执行完才会返回，即执行时间是该组任务中最慢的那个时间
    *  invokeAny   ---只支持callable ，只要有一个任务执行完成就返回
    *
    **/
public static final  ExecutorService POOL = new ThreadPoolExecutor(
        20,
        20,
        0,
        TimeUnit.MILLISECONDS,
        new LinkedBlockingDeque<>()
);

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        callableExecutor();

    }

    private void runnableExecutor(){
        MyRunnableTask myRunnableTask = null;
        List<MyRunnableTask> tasks = new ArrayList<>();
        for (int i=0 ; i < 10 ;i++){
            myRunnableTask = new MyRunnableTask(i);
            tasks.add(myRunnableTask);
        }

        for (MyRunnableTask task:tasks){
            POOL.execute(task);
        }
    }

    private static void callableExecutor() throws ExecutionException, InterruptedException {
        MyCallableTask myCallableTask = null;

        List<MyCallableTask<Integer>> tasks = new ArrayList<>();
        for (int i=0 ; i < 10 ;i++){
            myCallableTask = new MyCallableTask(i);
            tasks.add(myCallableTask);
        }

//        for (MyCallableTask task:tasks){
//            Future<Integer> future = POOL.submit(task);
//            Integer number = future.get();
//            System.out.println(number);
//        }
        //这里注意如果
//        List<Future<Integer>> futures = POOL.invokeAll(tasks);

        Integer integer1 = POOL.invokeAny(tasks);

        System.out.println(integer1);

//        for (Future<Integer> future:futures){
//            Integer integer = future.get();
//            System.out.println(integer);
//        }

    }



}
